# adoption from chapter 05 generate data.r
path_data=normalizePath('../../2021-2022(2)')
class_data_files = list.files(path_data)

library(readxl)
library(haven)
library(expss)
class_id = 2
xls_file = normalizePath(file.path(path_data,class_data_files[class_id]))
df_class_data = read_excel(xls_file,col_names = c('id','student_id','name'))

generate_data = function(seed_num,student_name){
  set.seed(seed_num)
  output_folder = file.path(getwd(),'data','chapter05',paste(seed_num,student_name,sep="_"))
  dir.create(file.path(getwd(),'data','chapter05'))
  dir.create(output_folder)
  treatment = c(rep(1,20),rep(2,20),rep(3,20))
  tr1 = ifelse(treatment==1,1,0) 
  tr2 = ifelse(treatment==2,1,0) 
  tr_c = ifelse(treatment==3,1,0) 
  gender_box = c(1,2)
  age = round(rnorm(60,25,2))
  gender = sample(gender_box,60,replace=TRUE)
  score = gender*30+age*15+tr1*70+tr2*35+rnorm(60,0,25)
  score = round(45+(score-min(score))/(max(score)-min(score))*55,1)
  
  df = data.frame(age=age,gender=factor(gender),group=factor(treatment),score=score)
  write_sav(df,file.path(output_folder,'ch5_exe_2.sav'))
  return(df)
}

for (row in 1:nrow(df_class_data)){
  student_id =as.numeric(df_class_data[row,'student_id']) %% 1000000
  name=df_class_data[row,'name']
  generate_data(student_id,name)
}
